import { computed, onBeforeMount } from 'vue'
// import { /* getLightColor, getDarkColor,*/ hexToRgb } from '@/utils/theme/tool'
import { addColorAlpha } from '@/utils/color'
import { GlobalStore } from '@/stores'
import { THEME_CONFIG } from '@/config/config'
import { ElMessage } from 'element-plus'

/**
 * @description 切换主题
 * */
export const useTheme = () => {
	const globalStore = GlobalStore()
	const themeConfig = computed(() => globalStore.themeConfig)

	// 切换暗黑模式
	const switchDark = () => {
		const html = document.documentElement as HTMLElement
		if (themeConfig.value.isDark) html.setAttribute('class', 'dark')
		else html.setAttribute('class', '')
	}

	// 修改主题颜色
	const changePrimary = (val: string) => {
		if (!val) {
			val = THEME_CONFIG.primary
			ElMessage({ type: 'success', message: `主题颜色已重置为 ${THEME_CONFIG.primary}` })
		}
		globalStore.setThemeConfig({ ...themeConfig.value, primary: val })
		// 颜色加深
		// document.documentElement.style.setProperty('--el-color-primary-dark-2', `${getDarkColor(themeConfig.value.primary, 0.1)}`)
		document.documentElement.style.setProperty('--el-color-primary', themeConfig.value.primary)
		// 颜色变浅
		for (let i = 1; i <= 9; i++) {
			document.documentElement.style.setProperty(
				`--el-color-primary-light-${i}`,
				`${addColorAlpha(themeConfig.value.primary, 1 - i / 10)}`
			)
		}
	}

	// 灰色和弱色切换
	const changeGreyOrWeak = (value: boolean, type: string) => {
		const body = document.body as HTMLElement
		if (!value) return body.setAttribute('style', '')
		if (type === 'grey') body.setAttribute('style', 'filter: grayscale(1)')
		if (type === 'weak') body.setAttribute('style', 'filter: invert(80%)')
		let propName = type == 'grey' ? 'isWeak' : 'isGrey'
		globalStore.setThemeConfig({ ...themeConfig.value, [propName]: false })
	}

	// 调整菜单圆角值
	const changeMenuRadius = (value: number) => {
		document.documentElement.style.setProperty('--sloth-side-menu-radius', value + 'px')
	}

	onBeforeMount(() => {
		switchDark()
		changePrimary(themeConfig.value.primary)
		changeMenuRadius(themeConfig.value.menuRadius)
		if (themeConfig.value.isGrey) changeGreyOrWeak(true, 'grey')
		if (themeConfig.value.isWeak) changeGreyOrWeak(true, 'weak')
	})

	return {
		switchDark,
		changePrimary,
		changeGreyOrWeak,
		changeMenuRadius
	}
}
